package nyu.edu.database.data.locks;

import java.util.ArrayList;

import nyu.edu.database.transaction.Transaction;

public class Lock {
	
	
	private ArrayList<Transaction> holdingTransactions;
	private LockType lockType;
	
	public Lock(){
		lockType = LockType.NONE;
		holdingTransactions = new ArrayList<Transaction>();
	}
	
	public boolean obtainReadLock(Transaction askingTransaction){
		if(lockType.equals(LockType.NONE)||lockType.equals(LockType.READ)){
			lockType=LockType.READ;
			holdingTransactions.add(askingTransaction);
			return true;
		}
		else{
			return false;
		}
	}
	
	public boolean releaseReadLock(Transaction askingTransaction){
		if(lockType.equals(LockType.READ) && holdingTransactions.contains(askingTransaction)){
			holdingTransactions.remove(holdingTransactions.indexOf(askingTransaction));
			if(holdingTransactions.size()==0){
				lockType=LockType.NONE;
			}
			return true;
		}
		else{
			return false;
		}
	}
	
	public boolean obtainWriteLock(Transaction askingTransaction){
		if(lockType.equals(LockType.NONE)){
			lockType=LockType.WRITE;
			holdingTransactions.add(askingTransaction);
			return true;
		}
		else{
			return false;
		}
	}
	
	public boolean releaseWriteLock(Transaction askingTransaction){
		if(lockType.equals(LockType.WRITE) && holdingTransactions.contains(askingTransaction)){
			holdingTransactions.remove(holdingTransactions.indexOf(askingTransaction));
			if(holdingTransactions.size()==0){
				lockType=LockType.NONE;
			}
			return true;
		}
		else{
			return false;
		}
	}
	
	private enum LockType{
		NONE, READ, WRITE
	}
}
